/**
 * 
 */
package ads.engenharia.dal;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import ads.engenharia.entity.Course;
import ads.engenharia.entity.Discipline;

/**
 * @author Lanedraex
 *
 */
public class CourseDisciplineDAO {

	private String sql;
	private String tableName = "\"Course_Discipline\"";

	private EntityManager em = new EntityManager() {

		@Override
		public Object treatResultSet(ResultSet resultSet) throws SQLException {
			Course course = new Course();

			course.program(searchCourseDisciplines(course.id()));
			return course;
		}
	};

	/**
	 * Saves the discipline for the course in the junction table.
	 * 
	 * @param course
	 * @throws SQLException
	 */
	public void save(Course course) throws SQLException {

		sql = " insert into " + tableName + " ( course_id, discipline_id )";

		for (Discipline discipline : course.program()) {

			em.executeQuery(sql, course.id(), discipline.id());

		}
	}

	/**
	 * 
	 * @param course
	 * @throws SQLException
	 */
	public void update(Course course) throws SQLException {

		sql = " update " + tableName
				+ " set discipline_id = ? where course_id = ? ";

		for (Discipline d : course.program()) {

			em.executeQuery(sql, d.id(), course.id());
		}
	}

	// TODO: disciplinas precisam de uma propriedade para indicar o semestre!
	/**
	 * Busca as disciplinas baseadas em um curso.
	 * 
	 * @param course
	 * @return
	 * @throws SQLException
	 */
	@SuppressWarnings("unchecked")
	public ArrayList<Discipline> searchCourseDisciplines(Course course)
			throws SQLException {

		sql = " select distinct discipline_id from " + tableName
				+ " where course_id = ? ";

		return (ArrayList<Discipline>) em.getResultList(sql, course.id());
	}

	/**
	 * 
	 * @param id
	 * @return
	 * @throws SQLException
	 */
	@SuppressWarnings("unchecked")
	public ArrayList<Discipline> searchCourseDisciplines(int id)
			throws SQLException {

		sql = " select distinct course_id from " + tableName
				+ " where course_id = ? ";

		return (ArrayList<Discipline>) em.getResultList(sql, id);
	}
}
